package com.glory.hikvisionmobile.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.activity.DialogActivity;
import com.glory.hikvisionmobile.activity.SopPdfActivity;
import com.glory.hikvisionmobile.adapter.PopListAdapter;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.DataCollect.XPdaComponentBean;
import com.glory.hikvisionmobile.bean.Login.LoginInfoBean;
import com.glory.hikvisionmobile.bean.TrackIn.SopDocumentBean;
import com.glory.hikvisionmobile.bean.from.UserBean;
import com.glory.hikvisionmobile.bean.from.UserListBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.adapter.FreeUI_NormalPopListAdapter;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils.setArrowMiss;

public class DialogUtils {
    public interface signCallback{
        void onSignSuccess();
    }
    public interface waferCallback{
        void onSuccess(boolean isChange);
    }

    public interface signCallback2{
        void onSignSuccess(String userID);
    }

    public interface popCallback{
        void onSuccess(List<String> list);
    }

    public static void showLoginDialog(Activity context, String userName, signCallback callback, FragmentManager fragmentManager){
        FreeUI_GeneralFragmentDialog freeU_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.dialog_login_sign,null);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        TextView tvConfirm = view.findViewById(R.id.tvConfirm);
        final FreeUI_ClearEditText etUserId = view.findViewById(R.id.etUserId);
        final FreeUI_ClearEditText etPwd = view.findViewById(R.id.etPwd);
        etUserId.setText(userName);
        etUserId.setFocusable(false);
        tvCancel.setOnClickListener(v -> freeU_generalFragmentDialog.dismiss());
        tvConfirm.setOnClickListener(v -> {
            String userId = etUserId.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(userId)) {
                FreeApi_ToastUtils.showFreeToast("请输入账号", context, false, FreeApi_StaticMembers.TOASTSHOWTIME);
                etUserId.requestFocus();
                return;
            }
            String pwd = etPwd.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(pwd)) {
                FreeApi_ToastUtils.showFreeToast("请输入密码", context, false, FreeApi_StaticMembers.TOASTSHOWTIME);
                etPwd.requestFocus();
                return;
            }

            JsonObject map = new JsonObject();
            map.addProperty("userName",etUserId.getText().toString().trim());
            map.addProperty("password",etPwd.getText().toString().trim());
            map.addProperty("actionType","Check");
            NetUtils.requestDara("HIK.PdaLogin", context, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<LoginInfoBean>>( new TypeToken<BaseResponseBean<LoginInfoBean>>() {
            }.getType(), fragmentManager, context) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LoginInfoBean>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(context.getApplicationContext(),false,fragmentManager)) {
                        freeU_generalFragmentDialog.dismiss();
                        callback.onSignSuccess();
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<LoginInfoBean>> response) {
                    super.onError(response);
                    FreeApi_LogUtils.saveErrorMessages(response.getException(), "HIK.PdaLogin");
                    FreeApi_ToastUtils.showFreeToast("连接服务器失败", context, false, FreeApi_StaticMembers.TOASTSHOWTIME);
                }
            });
        });
        freeU_generalFragmentDialog.setLayout(view);
        freeU_generalFragmentDialog.show(fragmentManager, "login_sign_dialog");

    }

    public static void showWaferDialog(Activity context,List<XPdaComponentBean> list, waferCallback callback, FragmentManager fragmentManager){
        Map<Integer,String> temporaryData = new HashMap<>();
        FreeUI_GeneralFragmentDialog freeU_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.dialog_wafer,null);
        RecyclerView wafer_Rv = view.findViewById(R.id.wafer_Rv);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        TextView tvConfirm = view.findViewById(R.id.tvConfirm);
        tvCancel.setOnClickListener(v -> freeU_generalFragmentDialog.dismiss());
        tvConfirm.setOnClickListener(v->{
            for (Map.Entry<Integer, String> entry : temporaryData.entrySet()) {
                list.get(entry.getKey()).setIsSelected(entry.getValue());
            }
            callback.onSuccess(temporaryData.size() != 0);
            freeU_generalFragmentDialog.dismiss();
        });
        wafer_Rv.setLayoutManager(new LinearLayoutManager(context));
        wafer_Rv.setItemAnimator(new DefaultItemAnimator());
        wafer_Rv.addItemDecoration(new DividerItemDecoration(context, 1));
        wafer_Rv.setAdapter(new BaseQuickAdapter<XPdaComponentBean, BaseViewHolder>(R.layout.adapter_wafer,list) {
            @Override
            protected void convert(BaseViewHolder helper, XPdaComponentBean item) {
                helper.setText(R.id.wafer_Name,item.getComponentId());
                helper.setChecked(R.id.wafer_Cx, item.getIsSelected().equals("Y"));
                helper.setOnCheckedChangeListener(R.id.wafer_Cx, (buttonView, isChecked) -> {
                    if (isChecked)
                        temporaryData.put(list.indexOf(item),"Y");
                    else
                        temporaryData.put(list.indexOf(item),"N");
                });
            }
        });
        freeU_generalFragmentDialog.setLayout(view);
        freeU_generalFragmentDialog.show(fragmentManager, "wafer_dialog");
    }

    public static FreeUI_GeneralFragmentDialog getScanDialog(final Context context, String tips, final FreeUI_TextCallback editTextScanCallback) {
        final FreeUI_GeneralFragmentDialog freeUI_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View contentView = LayoutInflater.from(context).inflate(R.layout.scan_dialog, null);
        TextView tvCancel = contentView.findViewById(R.id.tvCancel);
        TextView tvConfirm = contentView.findViewById(R.id.tvConfirm);
        final FreeUI_ClearEditText etScan = contentView.findViewById(R.id.etScan);
        etScan.setHint(tips);
        etScan.requestFocus();
        EditTextEnterUtils.initEnterToUpperCase(etScan);
        etScan.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (s.length() > 0) {
                        editTextScanCallback.onSuccess(s.toString());
                    } else {
                        FreeApi_ToastUtils.showFreeToast("输入信息有误", context, false, 0);
                    }
                }

            }

            public void afterTextChanged(Editable s) {
            }
        });
        tvCancel.setOnClickListener(v -> freeUI_generalFragmentDialog.dismiss());
        tvConfirm.setOnClickListener(v -> {
            if (etScan.getText().toString().trim().length() > 0) {
                editTextScanCallback.onSuccess(etScan.getText().toString().trim());
            } else {
                FreeApi_ToastUtils.showFreeToast("输入信息有误", context, false, 0);
            }

        });
        freeUI_generalFragmentDialog.setLayout(contentView);
        return freeUI_generalFragmentDialog;
    }

    public static void showLoginDialog(Activity context, signCallback2 callback, FragmentManager fragmentManager){
        FreeUI_GeneralFragmentDialog freeU_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.dialog_login_sign,null);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        TextView tvConfirm = view.findViewById(R.id.tvConfirm);
        final FreeUI_ClearEditText etUserId = view.findViewById(R.id.etUserId);
        final FreeUI_ClearEditText etPwd = view.findViewById(R.id.etPwd);
        tvCancel.setOnClickListener(v -> freeU_generalFragmentDialog.dismiss());
        tvConfirm.setOnClickListener(v -> {
            String userId = etUserId.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(userId)) {
                FreeApi_ToastUtils.showFreeToast("请输入账号", context, false, FreeApi_StaticMembers.TOASTSHOWTIME);
                etUserId.requestFocus();
                return;
            }
            if (userId.equals(Constant.CURRENT_USER)){
                FreeApi_ToastUtils.showFreeToast("确认人不能与操作人相同",context,false,0);
                return;
            }
            String pwd = etPwd.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(pwd)) {
                FreeApi_ToastUtils.showFreeToast("请输入密码", context, false, FreeApi_StaticMembers.TOASTSHOWTIME);
                etPwd.requestFocus();
                return;
            }

            JsonObject map = new JsonObject();
            map.addProperty("userName",etUserId.getText().toString().trim());
            map.addProperty("password",etPwd.getText().toString().trim());
            map.addProperty("actionType","Check");
            NetUtils.requestDara("HIK.PdaLogin", context, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<LoginInfoBean>>( new TypeToken<BaseResponseBean<LoginInfoBean>>() {
            }.getType(), fragmentManager, context) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LoginInfoBean>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(context.getApplicationContext(),false,fragmentManager)) {
                        freeU_generalFragmentDialog.dismiss();
                        callback.onSignSuccess(userId);
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<LoginInfoBean>> response) {
                    super.onError(response);
                    FreeApi_LogUtils.saveErrorMessages(response.getException(), "HIK.PdaLogin");
                    FreeApi_ToastUtils.showFreeToast("连接服务器失败", context, false, FreeApi_StaticMembers.TOASTSHOWTIME);
                }
            });
        });
        freeU_generalFragmentDialog.setLayout(view);
        freeU_generalFragmentDialog.show(fragmentManager, "login_sign_dialog");

    }

    public static void showSOPDialog(Activity context, List<SopDocumentBean> list, FragmentManager fragmentManager){
        FreeUI_GeneralFragmentDialog freeU_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.dialog_sop,null);
        RecyclerView rvSOP = view.findViewById(R.id.rvSOP);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        tvCancel.setOnClickListener(v -> freeU_generalFragmentDialog.dismiss());
        rvSOP.setLayoutManager(new LinearLayoutManager(context));
        rvSOP.setItemAnimator(new DefaultItemAnimator());
        rvSOP.addItemDecoration(new DividerItemDecoration(context, 1));
        rvSOP.setAdapter(new BaseQuickAdapter<SopDocumentBean, BaseViewHolder>(R.layout.adapter_wafer,list) {
            @Override
            protected void convert(BaseViewHolder helper, SopDocumentBean item) {
                helper.setText(R.id.wafer_Name,item.getFileName());
                helper.setGone(R.id.wafer_Cx,false);
                helper.setOnClickListener(R.id.wafer_Name, view1 -> {
                    if (FreeApi_StringUtils.isEmpty(item.getFilePath())){
                        FreeApi_ToastUtils.showFreeToast("当前文档未查询到路径",context,false,0);
                        return;
                    }

                    Bundle bundle = new Bundle();
                    bundle.putString("filePath",item.getFilePath());
                    bundle.putString("fileName",item.getFileName());
                    FreeApi_Utils.skipWithExtraIntent("header",bundle,context, SopPdfActivity.class);

                });

            }
        });
        freeU_generalFragmentDialog.setLayout(view);
        freeU_generalFragmentDialog.show(fragmentManager, "sop_dialog");
    }

    public static FreeUI_GeneralPop getManyChoosePop(List<UserBean> list,
                                                     Context context, final int width, final ImageView ivArrow, popCallback confirmListener) {
        final View mView = LayoutInflater.from(context).inflate(R.layout.pop_choose_list, null);
        RecyclerView recyclerView = mView.findViewById(R.id.rvList);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(context, 1));
        list.add(0,new UserBean("ALL"));
        PopListAdapter popListAdapter = new PopListAdapter(allCheck(list,true));
        TextView tvClose = mView.findViewById(R.id.tvClose);
        TextView tvConfirm = mView.findViewById(R.id.tvConfirm);
        final FreeUI_GeneralPop generalPop = new FreeUI_GeneralPop(context, mView
                , width, ViewGroup.LayoutParams.WRAP_CONTENT);
        recyclerView.setAdapter(popListAdapter);
        generalPop.setOutsideTouchable(true);
        generalPop.setOnDismissListener(() -> setArrowMiss(ivArrow));
        tvClose.setOnClickListener(view -> { allCheck(list,false);
            popListAdapter.notifyDataSetChanged();
        });
        popListAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position == 0){
                allCheck(adapter.getData(),true);
                adapter.notifyDataSetChanged();
            }
        });
        tvConfirm.setOnClickListener(view -> {
            List<String> result = new ArrayList<>();
            result.clear();
            List<UserBean> data = popListAdapter.getData();
            for (UserBean bean : data){
                if (bean.isChecked()){
                    result.add(bean.getDescription());
                }
            }
            confirmListener.onSuccess(result);
            generalPop.dismiss();
        });
        return generalPop;
    }

    private static List<UserBean> allCheck(List<UserBean> list,boolean isCheck) {
        for (UserBean bean : list){
            if (bean.getDescription().equals("ALL")){
                continue;
            }
            bean.setChecked(isCheck);
        }
        return list;
    }

    public static void setArrowMiss(View view) {
        RotateAnimation animationDismiss = new RotateAnimation(180.0F, 0.0F, 1, 0.5F, 1, 0.5F);
        animationDismiss.setDuration(500L);
        animationDismiss.setFillAfter(true);
        view.startAnimation(animationDismiss);
    }

    public static void setArrowShow(View view) {
        RotateAnimation animation = new RotateAnimation(0.0F, 180.0F, 1, 0.5F, 1, 0.5F);
        animation.setDuration(500L);
        animation.setFillAfter(true);
        view.startAnimation(animation);
    }

}
